package setting

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/response"
	"likeadmin/dao"
	"likeadmin/util"
)

const (
	RechargeStatusOn  = 1 // 状态开启
	RechargeStatusOff = 0 // 状态关闭
)

type IRechargeSettingService interface {
	Detail(c *gin.Context) (res resp.RechargeSettingResp, e error)
	Edit(c *gin.Context, editReq req.RechargeSettingEditReq) (e error)
}

// NewRechargeSettingService 初始化
func NewRechargeSettingService(db *gorm.DB, dao *dao.Query) IRechargeSettingService {
	return &rechargeSettingService{db: db, dao: dao}
}

// rechargeSettingService 通知设置服务实现类
type rechargeSettingService struct {
	db  *gorm.DB
	dao *dao.Query
}

// Detail 通知设置详情
func (srv rechargeSettingService) Detail(c *gin.Context) (res resp.RechargeSettingResp, e error) {
	str, err := util.ConfigUtil.GetVal(srv.db, "recharge", "config", "")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}
	var item resp.RechargeSettingResp
	_ = json.Unmarshal([]byte(str), &item)
	response.Copy(&res, item)
	return
}

// Edit 通知设置编辑
func (srv rechargeSettingService) Edit(c *gin.Context, editReq req.RechargeSettingEditReq) (e error) {
	marshal, err := json.Marshal(editReq)
	if err != nil {
		if e = response.CheckErr(err, "Save Set name err"); e != nil {
			return
		}
	}
	err = util.ConfigUtil.Set(srv.db, "recharge", "config", string(marshal))
	if e = response.CheckErr(err, "Save Set name err"); e != nil {
		return
	}

	util.RedisUtil.HDel("recharge", "config")
	return
}
